
#include "OiPCH.hpp"
#include "OiProfileDatabase.hpp"
#include <QSqlDatabase>
#include <QSqlQuery>

#define PROFILENAMEFORMAT "yyyy-MM-dd_hh-mm-ss-zzz.snp"
#define TIMESTAMPFORMAT "yyyyMMddhhmmsszzz"

namespace Oi
{
    namespace Appl
    {
        class ProfileDatabaseImpl : public Impl<ProfileDatabase>
        {
        public:
            void init(const QString&);
            void exit();

        public:
            QSqlDatabase _database;
            QString _path;
        };

        void ProfileDatabaseImpl::init(const QString& path)
        {
            _path = path;
            _database = QSqlDatabase::addDatabase("QSQLITE",  path + "/Profile.db");
            _database.setDatabaseName(path + "/Profile.db");
            _database.open();

            QSqlQuery query(_database);
            query.exec("CREATE TABLE IF NOT EXISTS profileTable (timestamp varchar(17), filepath varchar(260))");
        }

        void ProfileDatabaseImpl::exit()
        {
            _database.close();
        }

        ProfileDatabase::ProfileDatabase(QObject* parent, const QString& path) : QObject(parent)
        {
            OI_F(ProfileDatabase);
            d->init(path);
        }

        ProfileDatabase::~ProfileDatabase()
        {
            OI_E(ProfileDatabase)->exit();
        }

        void ProfileDatabase::addItem(const QDateTime& timestamp, const LTBase::MeasurementSnapShot& snapshot)
        {
            OI_F(ProfileDatabase);
            QSqlQuery query(d->_database);
            query.exec(QString("INSERT INTO profileTable (timestamp, filepath) VALUES (\"%1\", \"%2\")").arg(timestamp.toString(TIMESTAMPFORMAT)).arg(d->_path + "/" + timestamp.toString(PROFILENAMEFORMAT)));
        }

        void ProfileDatabase::deleteItem(const QDateTime& timestamp)
        {
            OI_F(ProfileDatabase);
            QSqlQuery query(d->_database);
            query.exec(QString("DELETE FROM profileTable WHERE timestamp=\"%1\"").arg(timestamp.toString(TIMESTAMPFORMAT)));
            QFile::remove(d->_path + "/" + timestamp.toString(PROFILENAMEFORMAT));
        }

        QList<QString> ProfileDatabase::searchItems(const QDateTime& startTime, const QDateTime& endTime)
        {
            OI_F(ProfileDatabase);

            QList<QString> results;
            QSqlQuery query(d->_database);

            query.exec(QString("SELECT * FROM profileTable WHERE timestamp  BETWEEN \"%1\" AND  \"%2\"").arg(startTime.toString(TIMESTAMPFORMAT)).arg(endTime.toString(TIMESTAMPFORMAT)));

            while (query.next())
            {
                QString timestamp = query.value(0).toString();
                OiWarning() << timestamp;
            }

            return QList<QString>();
        }

        

    }
}


